package com.smiletrain.activities;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import com.smiletrain.R;
import com.smiletrain.activities.base.AbstractActivity;
import com.smiletrain.util.AdminCasos;
import com.smiletrain.util.Constantes;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class PostFotosActivity extends AbstractActivity {
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(PostFotosActivity.this);
		builder.setTitle("ERROR")
			.setMessage("No se pudo cargar el caso para continuar con las Fotos Post Operatorias")
			.setCancelable(false)
			.setPositiveButton("Crear Nuevo Caso", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
					Intent intent = new Intent(PostFotosActivity.this, WellcomeActivity.class);
					startActivity(intent);
					finish();
				}
			});
		
		alert = builder.create();
		
		Intent inte = getIntent();
		int caso_id = 0;
		if(inte != null)
			caso_id = inte.getIntExtra("com.smiletrain.alarm.caso.id", 0);
		if(caso_id != 0){
			if(AdminCasos.instance.getCasos().length == 0)
				AdminCasos.instance.loadCasos();
			AdminCasos.instance.setCasoActual(caso_id);
			caso = AdminCasos.instance.getCasoActual();
		}
		if(caso_id != 0 && caso == null){
			alert.show();
		}
		
		if(caso == null){
			caso = AdminCasos.instance.getCasoActual();
			if(caso == null){
				Intent intent = new Intent(this, WellcomeActivity.class);
				startActivity(intent);
				finish();
				return;
			}
		}
		
		if(caso.getNumFotografias() == 1) {
			
			setContentView(R.layout.post_view_1);
			
			if(!caso.getPostFotos().getPathImage1().equals("")){
				ImageView pre1 = (ImageView) findViewById(R.id.bFrontal);
				MuestraFoto(caso.getPostFotos().getPathImage1(), pre1);
				toma1 = true;
			}
			
			iv1 = (ImageView) findViewById(R.id.bFrontal);
			
			if(caso.getPostFotos().getNameImage1().equals(""))
				realname1 = genFileName("frontal");
			else
				realname1 = caso.getPostFotos().getNameImage1();
			
			filename1 = Environment.getExternalStorageDirectory().getAbsolutePath()
					+ realname1;
			
			iv1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
					Uri output = Uri.fromFile(new File(filename1));
					
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					
					intent.putExtra(MediaStore.EXTRA_OUTPUT, output);

					startActivityForResult(intent, Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG01);
					
				}
				
			});
			
		} else {
			
			setContentView(R.layout.post_view_2);
			
			if(!caso.getPostFotos().getPathImage1().equals("")){
				ImageView pre1 = (ImageView) findViewById(R.id.bFrontal);
				MuestraFoto(caso.getPostFotos().getPathImage1(), pre1);
				toma1 = true;
			}
			
			if(!caso.getPostFotos().getPathImage2().equals("")){
				ImageView pre2 = (ImageView) findViewById(R.id.bOral);
				MuestraFoto(caso.getPostFotos().getPathImage2(), pre2);
				toma2 = true;
			}
			
			iv1 = (ImageView) findViewById(R.id.bFrontal);
			
			if(caso.getPostFotos().getNameImage1().equals(""))
				realname1 = genFileName("frontal");
			else
				realname1 = caso.getPostFotos().getNameImage1();
			
			filename1 = Environment.getExternalStorageDirectory().getAbsolutePath()
					+ realname1;
			
			iv1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
					Uri output = Uri.fromFile(new File(filename1));
					
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					
					intent.putExtra(MediaStore.EXTRA_OUTPUT, output);

					startActivityForResult(intent, Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG01);
					
				}
				
			});
			
			iv3 = (ImageView) findViewById(R.id.bOral);
			
			if(caso.getPostFotos().getNameImage2().equals(""))
				realname3 = genFileName("oral");
			else
				realname3 = caso.getPostFotos().getNameImage2();
			
			filename3 = Environment.getExternalStorageDirectory().getAbsolutePath()
					+ realname3;
			
			iv3.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
					Uri output = Uri.fromFile(new File(filename3));
					
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					
					intent.putExtra(MediaStore.EXTRA_OUTPUT, output);

					startActivityForResult(intent, Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG03);
					
				}
				
			});
		}
		
		super.setFootLayout();
		
		ImageView siguiente = (ImageView) findViewById(R.id.bSiguiente);
        
        siguiente.setOnClickListener(new OnClickListener() {
        	
			@Override
			public void onClick(View v) {
				
				updateCaso();
				
				if(!AdminCasos.validarPostFotos(caso)){
					Toast.makeText(PostFotosActivity.this, "Debe tomar las fotografías para poder continuar.", Toast.LENGTH_LONG).show();
				} else {
					Intent intent = new Intent(PostFotosActivity.this, FormularioActivity.class);
					startActivity(intent);
				}
				
			}
			
		});
        
	}
	
	@Override
	public void updateCaso() {
		if(!toma1){
			caso.getPostFotos().setPathImage1("");
			caso.getPostFotos().setNameImage1("");
		} else {
			caso.getPostFotos().setPathImage1(filename1);
			caso.getPostFotos().setNameImage1(realname1);
		}
		
		if(!toma2){
			caso.getPostFotos().setPathImage2("");
			caso.getPostFotos().setNameImage2("");
		} else {
			caso.getPostFotos().setPathImage2(filename3);
			caso.getPostFotos().setNameImage2(realname3);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		//Toast.makeText(this, "Result", Toast.LENGTH_LONG).show();
		switch (requestCode) {
			case Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG01:
				MuestraFoto(filename1, iv1);
				saveImage(filename1);
				toma1 = true;
				//MuestraFoto(imgFrontal1.getFileName(), imgFrontal1.getView());
				//view = (ImageView) findViewById(R.id.bFrontal1);
				//view.setImageBitmap(genImage(imgFrontal1.getFileName()));
				break;
			case Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG02:
				//MuestraFoto(filename2, iv2);
				break;
			case Constantes.ACTIVITY_TAKE_PICTURE_VIEW04_IMG03:
				MuestraFoto(filename3, iv3);
				saveImage(filename3);
				toma2 = true;
				break;
			default:
		}
		
	}
	
	private void MuestraFoto(String arch, ImageView view) {
		try {
			BitmapFactory.Options op = new BitmapFactory.Options();
			op.inJustDecodeBounds = true;
			int scale = 1;
			FileInputStream fd=new FileInputStream(arch);

			BitmapFactory.decodeFileDescriptor(fd.getFD(),null,op);
			
			if (op.outHeight > Constantes.IMAGE_MAX_SIZE || op.outWidth > Constantes.IMAGE_MAX_SIZE) {
				double d = Math.pow(2, (int) Math.round(Math.log(Constantes.IMAGE_MAX_SIZE / (double) Math.max(op.outHeight, op.outWidth)) / Math.log(0.5)));
				scale = (int) d;
			}
			
			op = new BitmapFactory.Options();
			op.inSampleSize = scale;

			view.setImageBitmap(BitmapFactory.decodeFileDescriptor(fd.getFD(),null,op));
			
			fd.close();
			
		} catch(Exception e) {
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
		}
	}
	
	private String genFileName(String aux) {
		Long date = new Date().getTime();
		String sdate = date.toString();
		String name = Constantes.IMAGE_PATH
				+ "imgst.post." + aux + "."
				+ sdate.substring(sdate.length() - 6, sdate.length() - 2);
		name += ".jpg";
		return name;
	}
	
	private void saveImage(String pathfilename) {
		File dest = new File(pathfilename);

		Bitmap bitmap = buildBitmap(pathfilename);
		
		try {
		     FileOutputStream out = new FileOutputStream(dest);
		     bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out);
		     out.flush();
		     out.close();
		} catch (Exception e) {
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
		}
		
		if(bitmap != null)
			bitmap.recycle();
	}
	
	private Bitmap buildBitmap(String arch) {
		Bitmap res = null;
		BitmapFactory.Options op = new BitmapFactory.Options();
		op.inJustDecodeBounds = true;

		try {
			
			FileInputStream fd = new FileInputStream(arch);
			BitmapFactory.decodeFileDescriptor(fd.getFD(), null, op);
			op = new BitmapFactory.Options();
		
			res = BitmapFactory.decodeFileDescriptor(fd.getFD(),null,op);
			
		} catch (IOException e) {
			Toast.makeText(this, e.toString(), Toast.LENGTH_LONG);
		}
		
		return res;
	}
	
	private ImageView iv1, iv3;
	private String filename1 = "", filename3 = "";
	private String realname1 = "", realname3 = "";
	private boolean toma1 = false, toma2 = false;
	private AlertDialog alert;
	
}
